package com.junzhiit.nengji.shop.dao.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.bainaeco.framework.base.dao.AbstractBaseDAO;
import com.bainaeco.framework.common.jdbc.StatementParameter;
import com.junzhiit.nengji.shop.bo.RedeemCodeBO;
import com.junzhiit.nengji.shop.dao.RedeemCodeDAO;
import com.junzhiit.nengji.shop.model.RedeemCode;
import com.junzhiit.nengji.shop.model.enums.Is;

@Repository
public class RedeemcodeDAOImpl extends AbstractBaseDAO<RedeemCode> implements RedeemCodeDAO {

	@Override
	public RedeemCodeBO checkEffective(String redeemCode) {
		StringBuffer sql = new StringBuffer();
		StatementParameter param = new StatementParameter();
		sql.append(" select c.*,rc.`code` redeemCode,rc.is_delete redeemCodeDelete from redeem_code rc left join coupons c on rc.coupons_id = c.id ");
		sql.append(" where rc.`code` = ? and c.`status`= ? ");
		sql.append(" and (c.valid_end_time > now() or (c.valid_days is not null  and c.valid_days > ?) ) ");
		param.setString(redeemCode);
		param.setInt(Is.YES.toIntValue());
		param.setInt(Is.NO.toIntValue());
		return super.query(sql.toString(), RedeemCodeBO.class, param);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public boolean isDelete(String redeemCode) {
		StatementParameter param = new StatementParameter();
		String sql = "update redeem_code set is_delete = ? where code = ? ";
		param.setInt(Is.YES.toIntValue());
		param.setString(redeemCode);
		return super.updateForRecord(sql, param)>0;
	}

	@Override
	public RedeemCodeBO checkReceive(String redeemCode, String csId,Integer isChain) {
		StringBuffer sql = new StringBuffer();
		StatementParameter param = new StatementParameter();
		sql.append(" select c.*,rc.`code` redeemCode,rc.is_delete redeemCodeDelete from redeem_code rc left join coupons c on rc.coupons_id = c.id ");
		sql.append(" where rc.`code` = ? and c.`status`= ? ");
		sql.append(" and (c.valid_end_time > now() or (c.valid_days is not null  and c.valid_days > ?) ) ");
		param.setString(redeemCode);
		param.setInt(Is.YES.toIntValue());
		param.setInt(Is.NO.toIntValue());
		
		if( isChain == Is.NO.toIntValue() ){
			if(StringUtils.isNotBlank(csId)){
				sql.append(" and c.shop_id = ? ");
				param.setString(csId);
			}
		}else{
			if(StringUtils.isNotBlank(csId)){
				sql.append(" and c.chain_id = ? ");
				param.setString(csId);
			}
		}
		
		return super.query(sql.toString(), RedeemCodeBO.class, param);
	}

}
